package safeCommitter.test.finder.simple;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.search.MethodReferenceMatch;
import org.eclipse.jdt.core.search.SearchMatch;
import org.eclipse.jdt.core.search.SearchRequestor;
import org.eclipse.jdt.internal.core.SourceField;

import safeCommitter.model.adpters.SCSingleMethodTest;
import safeCommitter.test.finder.core.ISCMethodRepository;
import safeCommitter.utils.SCUtils;

public class SCSimpleSearchRequestor extends SearchRequestor {

	private final ISCMethodRepository repository;

	public SCSimpleSearchRequestor(final ISCMethodRepository repository) {
		this.repository = repository;
	}

	@Override
	public void acceptSearchMatch(final SearchMatch match) throws CoreException {
		if (!(match instanceof MethodReferenceMatch))
			return;
		if (match.getElement() instanceof SourceField)
			return;
		IMethod methodFound = (IMethod) match.getElement();
		if (repository.alreadySearched(methodFound)) {
			return;
		}
		addRecursiveInfo(methodFound);
	}

	private void addRecursiveInfo(final IMethod methodFound) {
		if (SCUtils.isTestMethod(methodFound)) {
			repository.addTest(new SCSingleMethodTest(methodFound));
		} else {
			repository.addCalledMethod(methodFound);
		}
	}

}
